package com.zp.security.oauth2.customized;

import com.zp.security.oauth2.customized.service.EmailCodeUserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Objects;


/**
 * 自定义AuthenticationProvider，类似于DaoAuthenticationProvider
 *
 * @author zp
 */
public class EmailAuthenticationProvider implements AuthenticationProvider {
    private final EmailCodeUserDetailService emailCodeUserDetailService;
    private final PasswordEncoder passwordEncoder;
    public EmailAuthenticationProvider(EmailCodeUserDetailService emailCodeUserDetailService,PasswordEncoder passwordEncoder){
        this.emailCodeUserDetailService=emailCodeUserDetailService;
        this.passwordEncoder=passwordEncoder;
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        EmailAuthenticationToken authenticationToken= (EmailAuthenticationToken) authentication;
        String email = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        UserDetails userDetails = emailCodeUserDetailService.loadUserByEmail(email);
        if (Objects.isNull(userDetails)){
            throw new InternalAuthenticationServiceException("该用户不存在");
        }
        if (!passwordEncoder.matches(password,userDetails.getPassword())){
            throw new BadCredentialsException("密码错误");
        }
        EmailAuthenticationToken emailAuthenticationToken=new EmailAuthenticationToken(email,password,userDetails.getAuthorities());
        emailAuthenticationToken.setDetails(authentication.getDetails());
        emailAuthenticationToken.setAuthenticated(true);
        return emailAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return EmailAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
